# -*- coding: utf-8 -*-
import os
import time
import logging
import inspect
from logging.handlers import RotatingFileHandler

dir = os.path.dirname(__file__)
dir_time = time.strftime('%Y-%m-%d', time.localtime())

consoleLog = logging.StreamHandler()
consoleLog.setLevel(logging.INFO)
logging.getLogger('').addHandler(consoleLog)

# FORMAT = '%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s'
# DATEFMT = '%Y-%m-%d %H:%M:%S'
# # 配置log日志功能
# logging.basicConfig(level=log.info,
#                     filename="./log.txt",
#                     filemode="a",
#                     format=FORMAT)
# logging.basicConfig(level=log.error,
#                     filename="./error.txt",
#                     filemode="a",
#                     format=FORMAT)
# consoleLog = logging.StreamHandler()
# consoleLog.setLevel(logging.DEBUG)
# consoleLog.setFormatter(logging.Formatter(FORMAT,DATEFMT))
# logging.getLogger('').addHandler(consoleLog)

handlers = {
    logging.CRITICAL: os.path.join(dir, '../log/critical/%s.log'%dir_time),
    logging.FATAL: os.path.join(dir, '../log/fatal/%s.log'%dir_time),
    logging.ERROR: os.path.join(dir, '../log/error/%s.log'%dir_time),
    logging.WARNING: os.path.join(dir, '../log/warning/%s.log'%dir_time),
    logging.INFO: os.path.join(dir, '../log/info/%s.log'%dir_time),
    logging.DEBUG: os.path.join(dir, '../log/debug/%s.log'%dir_time),
    logging.NOTSET: os.path.join(dir, '../log/notset/%s.log'%dir_time),
}

def project_root_path(project_name=None, print_log=True):
    """
    获取当前项目根路径
        :param project_name: 项目名称
            1、可在调用时指定
            2、[推荐]也可在此方法中直接指定 将'XmindUitl-master'替换为当前项目名称即可（调用时即可直接调用 不用给参数）
        :param print_log: 是否打印日志信息
        :return: 指定项目的根路径
    """
    p_name = 'company-crawler1' if project_name is None else project_name
    project_path = os.path.abspath(os.path.dirname(__file__))
    # Windows
    if project_path.find('\\') != -1: separator = '\\'
    # Mac、Linux、Unix
    if project_path.find('/') != -1: separator = '/'

    root_path = project_path[:project_path.find(f'{p_name}{separator}') + len(f'{p_name}{separator}')]
    if print_log: print(f'当前项目名称：{p_name}\r\n当前项目根路径：{root_path}')
    return root_path

def createHandlers():
    logLevels = handlers.keys()

    for level in logLevels:
        path = os.path.abspath(handlers[level])
        isexists_dir_Create(path),
        handlers[level] = RotatingFileHandler(path, backupCount=2, encoding='utf-8')

'''
    判断文件是否存在，存在无效果，不存在则生成文件夹
    path:路径的绝对路径，通过获取当前文件的绝对路径，再将文件夹文件拼接起来
'''
def isexists_dir_Create(path):
     if not os.path.exists(path[:-15]):
        os.makedirs(path[:-15])
    # if os.path.exists(path):
    #     with open(path,mode='r',encoding='utf-8') as ff:
    #         print(ff.readlines())
    #         print("文件已存在！")
    # else:
    #     with open(path, mode='w', encoding='utf-8') as ff:
    #         print("文件创建成功！")

# 加载模块时创建全局变量
createHandlers()

class TNLog(object):

    def printfNow(self):
        return time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())

    def __init__(self, level=logging.NOTSET):
        self.__loggers = {}

        logLevels = handlers.keys()

        for level in logLevels:
            logger = logging.getLogger(str(level))

            # 如果不指定level，获得的handler似乎是同一个handler?

            logger.addHandler(handlers[level])

            logger.setLevel(level)

            self.__loggers.update({level: logger})

    def getLogMessage(self, level, message):
        frame, filename, lineNo, functionName, code, unknowField = inspect.stack()[2]

        '''日志格式：[时间] [类型] [记录代码] 信息'''
        # return "[%s] [%s - %s] [%s] %s" % (self.printfNow(), filename, lineNo, level, message)
        return '[%s] ["%s", line %s] [%s] %s' % (self.printfNow(), filename, lineNo, level, message)

    def critical(self, message):
        message = self.getLogMessage("critical", message)
        self.__loggers[logging.CRITICAL].critical(message)

    def fatal(self, message):
        message = self.getLogMessage("fatal", message)
        self.__loggers[logging.FATAL].fatal(message)

    def error(self, message):
        message = self.getLogMessage("error", message)
        self.__loggers[logging.ERROR].error(message)
        self.__loggers[logging.DEBUG].debug(message)

    def warning(self, message):
        message = self.getLogMessage("warning", message)
        self.__loggers[logging.WARNING].warning(message)

    def info(self, message):
        message = self.getLogMessage("info", message)
        self.__loggers[logging.INFO].info(message)
        self.__loggers[logging.DEBUG].debug(message)

    def debug(self, message):
        message = self.getLogMessage("debug", message)
        self.__loggers[logging.DEBUG].debug(message)

if __name__ == "__main__":
    logger = TNLog()

    logger.debug("debug")
    logger.info("info")
    logger.warning("warning")
    logger.error("error")
    logger.critical("critical")